using Microsoft.AspNetCore.Mvc;
using MVCWeekOne.Models;
using System.Text;
using System.Text.Json;

namespace MVCWeekOne.Controllers
{
    public class WorkTaskController : Controller
    {
        private readonly HttpClient _httpClient;
        private readonly string _readBaseUrl = "http://localhost:5089/api";  // 读操作端口（查询）
        private readonly string _writeBaseUrl = "http://localhost:5090/api"; // 写操作端口（删除）

        public WorkTaskController()
        {
            _httpClient = new HttpClient();
        }

        /// <summary>
        /// 任务管理页面
        /// </summary>
        public IActionResult Index()
        {
            ViewData["Title"] = "任务管理";
            return View();
        }

        /// <summary>
        /// 获取任务分页数据
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> GetWorkTaskPage([FromBody] WorkTaskQueryModel query)
        {
            try
            {
                Console.WriteLine($"开始查询任务数据，查询参数: {JsonSerializer.Serialize(query)}");
                
                var json = JsonSerializer.Serialize(query);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                
                var apiUrl = $"{_readBaseUrl}/WorkTask/query"; // 使用读端口
                Console.WriteLine($"查询API地址: {apiUrl}");
                
                var response = await _httpClient.PostAsync(apiUrl, content);
                var result = await response.Content.ReadAsStringAsync();
                
                Console.WriteLine($"查询API响应状态: {response.StatusCode}");
                Console.WriteLine($"查询API响应内容: {result}");
                
                return Content(result, "application/json");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"查询API调用异常: {ex.Message}");
                return Json(new { code = 500, msg = $"查询失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 获取所有角色
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetRoleAll()
        {
            try
            {
                var apiUrl = $"{_readBaseUrl}/Role/GetRoleAll"; // 使用读端口
                Console.WriteLine($"角色API地址: {apiUrl}");
                
                var response = await _httpClient.GetAsync(apiUrl);
                var result = await response.Content.ReadAsStringAsync();
                
                Console.WriteLine($"角色API响应状态: {response.StatusCode}");
                Console.WriteLine($"角色API响应内容: {result}");
                
                return Content(result, "application/json");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"角色API调用异常: {ex.Message}");
                return Json(new { code = 500, msg = $"查询失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 获取不良品项列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetDefectiveList(int index = 1, int size = 100, string defectiveCode = "", string defectiveName = "")
        {
            try
            {
                var url = $"{_readBaseUrl}/Defective/GetPage?Index={index}&Size={size}"; // 使用正确的接口路径
                if (!string.IsNullOrEmpty(defectiveCode))
                    url += $"&DefectiveCode={defectiveCode}";
                if (!string.IsNullOrEmpty(defectiveName))
                    url += $"&DefectiveName={defectiveName}";

                Console.WriteLine($"不良品项API地址: {url}");
                var response = await _httpClient.GetAsync(url);
                var result = await response.Content.ReadAsStringAsync();
                
                Console.WriteLine($"不良品项API响应状态: {response.StatusCode}");
                Console.WriteLine($"不良品项API响应内容: {result}");
                
                return Content(result, "application/json");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"不良品项API调用异常: {ex.Message}");
                return Json(new { code = 500, msg = $"查询失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 批量删除任务
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> BatchDelete([FromBody] BatchDeleteRequest request)
        {
            try
            {
                Console.WriteLine($"开始调用删除API，请求参数: {JsonSerializer.Serialize(request)}");
                
                var json = JsonSerializer.Serialize(request);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                
                var apiUrl = $"{_writeBaseUrl}/WorkTask/BatchDelete"; // 使用写端口
                Console.WriteLine($"删除API地址: {apiUrl}");
                
                // 使用DELETE方法调用删除API，但通过POST传递请求体
                var requestMessage = new HttpRequestMessage(HttpMethod.Delete, apiUrl);
                requestMessage.Content = content;
                
                Console.WriteLine($"发送删除请求...");
                var response = await _httpClient.SendAsync(requestMessage);
                var result = await response.Content.ReadAsStringAsync();
                
                Console.WriteLine($"删除API响应状态: {response.StatusCode}");
                Console.WriteLine($"删除API响应内容: {result}");
                
                return Content(result, "application/json");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"删除API调用异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return Json(new { code = 500, msg = $"删除失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 更新任务
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> UpdateWorkTask([FromBody] UpdateWorkTaskRequest request)
        {
            try
            {
                Console.WriteLine($"开始调用更新API，请求参数: {JsonSerializer.Serialize(request)}");
                
                var json = JsonSerializer.Serialize(request);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                
                var apiUrl = $"{_writeBaseUrl}/WorkTask/Update"; // 使用写端口
                Console.WriteLine($"更新API地址: {apiUrl}");
                
                // 使用PUT方法调用更新API
                var requestMessage = new HttpRequestMessage(HttpMethod.Put, apiUrl);
                requestMessage.Content = content;
                
                Console.WriteLine($"发送更新请求...");
                var response = await _httpClient.SendAsync(requestMessage);
                var result = await response.Content.ReadAsStringAsync();
                
                Console.WriteLine($"更新API响应状态: {response.StatusCode}");
                Console.WriteLine($"更新API响应内容: {result}");
                
                return Content(result, "application/json");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"更新API调用异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return Json(new { code = 500, msg = $"更新失败：{ex.Message}" });
            }
        }
    }

    /// <summary>
    /// 批量删除请求模型
    /// </summary>
    public class BatchDeleteRequest
    {
        public List<long> ids { get; set; } = new List<long>();
        public string deleter { get; set; } = "";
    }

    /// <summary>
    /// 更新任务请求模型
    /// </summary>
    public class UpdateWorkTaskRequest
    {
        public long id { get; set; }
        public long processId { get; set; }
        public string allocationList { get; set; } = "";
        public string plannedStartTime { get; set; } = "";
        public string plannedEndTime { get; set; } = "";
        public int plannedQuantity { get; set; }
        public int goodQuantity { get; set; }
        public int defectiveQuantity { get; set; }
        public string actualStartTime { get; set; } = "";
        public string actualEndTime { get; set; } = "";
        public string updator { get; set; } = "";
    }
    
} 